<template>
    <el-dialog
        :visible="show"
        destroy-on-close
        center
        append-to-body
        modal
        title="视频上传"
        width="720px"
        v-loading="loading"
        element-loading-text="拼命加载中"
        element-loading-spinner="el-icon-loading"
        element-loading-background="rgba(0, 0, 0, 0.8)"
        @close="$emit('close')"
    >
        <input
            type="file"
            @change="onFileChange"
            ref="uploadRef"
            class="media-input"
            accept="video/*"
            multiple="multiple"
        />
        <div class="upload-image-box">
            <div class="media-box-item" @click="onImgClick">
                <div class="media-img">
                    点击上传
                </div>
            </div>
            <div class="media-box-item" v-for="(item) in files" :key="item.name">
                <i class="el-icon-close media-item-close" @click="deleteFiles(item)"></i>
                <img :src="item.src" :style="item|imgStyle"/>
            </div>
        </div>
        <div class="flag-box">
            <div v-for="item in flags" :key="item" class="flag-item">
                <i class="el-icon-close flag-item-close" @click="deleteFlag(item)" />
                {{item}}
            </div>
            <el-input
                class="flag-input"
                size="small"
                placeholder="请输入资源标签，用逗号，或分号；分割"
                @input="tapInFlag"
                :value="flagStr"
            />
        </div>
        <div slot="footer" class="footer-buttons">
            <el-button @click="$emit('close')" >取消</el-button>
            <el-button @click="uploadFile" type="success">确定</el-button>
        </div>
    </el-dialog>
    
</template>

<script>
import axios from 'axios';
export default {
    props: ['show'],
    data() {
        return {
            files: [],
            flags: [],
            flagStr: '',
            loading: false,
        }
    },
    filters: {
        imgStyle(item) {
            const { width, height } = item;
            if (width / 16 > height / 9) {
                return {
                    width: '100%',
                };
            } else {
                return {
                    height: '100%',
                };
            }
        }
    },
    methods: {
        deleteFlag(flag) {
            const flagIndex = this.flags.findIndex(vo => vo === flag);
            if (flagIndex >= 0) {
                this.flags.splice(flagIndex, 1);
            }
        },
        onImgClick() {
            this.$refs.uploadRef.click();
        },
        deleteFiles(file) {
            const fileIndex = this.files.findIndex(vo => vo.name === file.name);
            if (fileIndex >= 0) {
                this.files.splice(fileIndex, 1);
            }
        },
        tapInFlag(value) {
            if ([',', ';', '，', '；'].includes(value.substr(value.length - 1))) {
                const flag = value.substr(0, value.length - 1);
                if (this.flags.findIndex(vo => vo === flag) < 0) {
                    this.flags.push(flag);
                }
                this.flagStr = '';
            } else {
                this.flagStr = value;
            }
        },
        onFileChange(e) {
            const { files } = e.target;
            for (let i = 0; i < files.length; i += 1) {
                if (this.files.findIndex(vo => vo.name === files[i].name) >= 0) {
                    continue;
                }
                const file = files[i];
                const videoObjUrl = URL.createObjectURL(file);
                let seekResolve;
                const video = document.createElement('video');
                video.addEventListener('seeked', () => {
                if (seekResolve) seekResolve();
                });
                video.addEventListener('loadeddata', async () => {
                    const [w, h] = [video.videoWidth, video.videoHeight];
                    const duration = video.duration;
                    let canvas = document.createElement('canvas');
                    let context = canvas.getContext('2d');
                    video.currentTime = 0;
                    await new Promise(r => seekResolve = r);
                    context.drawImage(video, 0, 0, w, h);
                    const imgData = canvas.toDataURL("image/png");
                    this.files.push({
                        file: files[i],
                        name: files[i].name,
                        src: imgData,
                        width: w,
                        height: h,
                    });
                });
                video.src = videoObjUrl;
            }
        },
        uploadFile() {
            const forms = new FormData();
            const configs = {
                headers: { 'Content-Type': 'multipart/form-data' }
            };
            for (let i = 0; i < this.files.length; i += 1) {
                forms.append('file', this.files[i].file);
            }
            forms.append('flag', this.flags);
            forms.append('meta', 'video');
            this.loading = true;
            axios.post('/api/upload', forms, configs).then((res) => {
                const { code } = res.data;
                if (Number(code) === 0) {
                    this.$message({
                        type: 'success',
                        message: '上传成功',
                    });
                    this.loading = false;
                    this.$emit('success');
                    this.files = [];
                } else {
                    this.$message.error('上传失败');
                    this.loading = false;
                }
            });
        }
    }
}
</script>

<style lang="less" scoped>
.media-input {
    width: 0;
    height: 0;
    display: inline-block;
    visibility: hidden;
}
.upload-image-box {
    border: solid 1px #F3F3F3;
    height: 320px;
    overflow: auto;
    padding: 8px 12px;
    &::-webkit-scrollbar {
        border-radius: 100%;
    }
    .media-box-item {
        width: 120px;
        height: 68px;
        display: inline-block;
        margin: 8px;
        display: flex;
        align-items: center;
        justify-content: center;
        float: left;
        border: solid 1px #F3F3F3;
        position: relative;
        .media-item-close {
            position: absolute;
            right: 0;
            top: 0;
            display: none;
            border-radius: 100%;
            transform: translate(50%, -50%);
            padding: 4px;
            background: #EFEFEF;
        }
        &:hover .media-item-close {
            display: inline-block;
        }
        .media-img {
            width: 100%;
            height: 100%;
            display: flex;
            align-items: center;
            justify-content: center;
        }
    }
}
.footer-buttons {
    text-align: right;
}
.flag-box {
    display: flex;
    align-items: center;
    margin: 12px 0;
    .flag-item {
        margin-right: 12px;
        padding: 4px 12px;
        background: #EFEFEF;
        position: relative;
        font-size: 12px;
        .flag-item-close {
            position: absolute;
            top: 2px;
            right: 2px;
            display: none;
            font-size: 12px;
        }
        &:hover .flag-item-close {
            display: inline-block;
        }
    }
    .flag-input {
        flex: 1;
    }
}
/deep/ .el-dialog__footer {
    background: #FEFEFE;
}
</style>
